import React, { useState, useRef, useEffect } from 'react';
import { Modal, Input, Button, App } from 'antd';
import {
  MinusCircleFilled,
  PlusCircleFilled,
  CloseOutlined,
  SearchOutlined,
} from '@ant-design/icons';
import ImportGuideModal from './ImportGuideModal';

interface InputGuide {
  id: string;
  content: string;
}

interface InputGuideModalProps {
  visible: boolean;
  onClose: () => void;
  initialGuides?: InputGuide[];
  onSave: (guides: InputGuide[]) => void;
}

const InputGuideModal: React.FC<InputGuideModalProps> = ({
  visible,
  onClose,
  initialGuides = [],
  onSave,
}) => {
  const [guides, setGuides] = useState<InputGuide[]>(initialGuides);
  const [newGuide, setNewGuide] = useState('');
  const [searchText, setSearchText] = useState('');
  const [importModalVisible, setImportModalVisible] = useState(false);
  const { message } = App.useApp();

  useEffect(() => {
    setGuides(initialGuides);
  }, [initialGuides]);

  useEffect(() => {
    if (visible) {
      setGuides(initialGuides)
      setNewGuide('');
      setSearchText('')
    }
  }, [visible]);

  const addGuide = () => {
    if (!newGuide.trim()) {
      message.warning('引导内容不能为空');
      return;
    }

    // 检查问题是否重复
    const isDuplicate = guides.some(q => q.content === newGuide.trim());
    if (isDuplicate) {
      message.warning('引导内容不能重复');
      return;
    }

    const newId = Date.now().toString();
    setGuides([{ id: newId, content: newGuide }, ...guides]);
    setNewGuide('');
  };

  const deleteGuide = (id: string) => {
    setGuides(guides.filter((g) => g.id !== id));
  };

  const updateGuide = (id: string, content: string) => {
    setGuides(guides.map((g) => (g.id === id ? { ...g, content } : g)));
  };

  const handleSave = () => {
    let finalGuides = [...guides];

    // 如果 newGuide 不为空，添加到 guides
    if (newGuide.trim()) {
      finalGuides.push({
        id: Date.now().toString(),
        content: newGuide.trim()
      });
    }


    // 根据 content 去重
    finalGuides = Array.from(
      new Map(finalGuides.map(guide => [guide.content, guide])).values()
    );

    onSave(finalGuides);
    setNewGuide('');
    onClose();
  };

  // 过滤搜索结果
  const filteredGuides = searchText
    ? guides.filter((guide) => guide.content.toLowerCase().includes(searchText.toLowerCase()))
    : guides;

  const handleFileImport = () => {
    setImportModalVisible(true);
  };

  const handleImportClose = () => {
    setImportModalVisible(false);
  };

  const handleImportContent = (content: string) => {
    // 按行分割文件内容并检查乱码
    const lines = content.split(/\r?\n/).filter(line => line.trim() !== '');

    // 检查是否存在乱码
    const hasInvalidChars = lines.some(line => {
      const trimmedLine = line.trim();
      // 检查是否包含非法字符，但允许更多合法的Unicode字符
      return !/^[\p{L}\p{N}\p{P}\p{Z}\p{S}]+$/u.test(trimmedLine);
    });
    if (hasInvalidChars) {
      console.log('hasInvalidChars', lines);
      message.error('文件内容包含无法解析的字符，请确保内容格式正确！');
      return;
    }


    if (lines.length === 0) {
      message.warning('文件中没有有效内容');
      return;
    }

    // 添加每一行作为引导
    const newGuides = lines.map((line) => ({
      id: Date.now() + Math.random().toString(36).substring(2, 9),
      content: line.trim().slice(0, 50), // 限制最大长度为50个字符
    }));

    // 检查并过滤掉重复内容
    const uniqueGuides = newGuides.filter((guide, index, self) =>
      index === self.findIndex((g) => g.content === guide.content)
    );


    // 获取现有引导的内容集合
    const existingContents = new Set(guides.map(guide => guide.content));

    // 过滤掉已存在的内容
    const uniqueNewGuides = uniqueGuides.filter(guide => !existingContents.has(guide.content));

    // 更新引导列表
    setGuides(prev => [...uniqueNewGuides, ...prev]);

    // 显示导入结果
    if (uniqueNewGuides.length === 0) {
      message.warning('没有新的引导问题被导入，所有内容都已存在');
    } else if (newGuides.length > uniqueNewGuides.length) {
      message.success(`成功导入 ${uniqueNewGuides.length} 条新引导，${newGuides.length - uniqueNewGuides.length} 条重复内容已跳过`);
    } else {
      message.success(`成功导入 ${uniqueNewGuides.length} 条新引导`);
    }
  };

  // 输入框自定义样式
  const inputStyle = {
    background: '#F1F3F9',
    border: 'none',
    borderColor: 'transparent',
    boxShadow: 'none',
    padding: '8px', // 给图标留足空间
    borderRadius: '8px',
  };

  // 搜索框样式
  const searchInputStyle = {
    background: '#FDFDFD',
    border: '1px solid #E5E6EB',
    boxShadow: 'none',
    padding: '8px 12px',
    borderRadius: '8px',
  };

  // 引导列表项样式
  const guideInputStyle = {
    background: 'transparent',
    border: 'none',
    borderColor: 'transparent',
    boxShadow: 'none',
    padding: '0',
    color: '#424242',
  };

  return (
    <>
      <Modal
        title={
          <div className="items-left flex flex-col">
            <div className="text-lg font-medium">输入引导</div>
            <div className="mt-1 text-[11px] font-normal text-[#A5A9BB]">
              配置后用户输入问题时自动展开下方配置的引导问题，便于用户快速提问
            </div>
          </div>
        }
        open={visible}
        onCancel={onClose}
        width={610}
        centered
        footer={null}
        closeIcon={<CloseOutlined className="text-[#86909C]" />}
        bodyStyle={{ padding: '10px 0 24px 0' }}
      >
        <div className="flex h-full flex-col" style={{ maxHeight: '80vh' }}>
          <div>
            {/* 搜索框 */}
            <div className="mb-4">
              <div className="relative">
                <Input
                  prefix={<SearchOutlined className="text-[#86909C]" />}
                  placeholder="搜索输入引导"
                  value={searchText}
                  onChange={(e) => setSearchText(e.target.value)}
                  style={searchInputStyle}
                  className="!border-[#E5E6EB] !bg-[#FDFDFD]" // 使用!important覆盖Ant Design样式
                />
              </div>
            </div>

            {/* 新增引导输入框 */}
            <div className="mb-4">
              <div className="relative">
                <Input
                  placeholder="点击这里输入新的引导，点击回车键（Enter键）确定"
                  value={newGuide}
                  onChange={(e) => setNewGuide(e.target.value)}
                  onPressEnter={addGuide}
                  maxLength={50}
                  style={inputStyle}
                  className="!border-none !bg-[#F1F3F9]" // 使用!important覆盖Ant Design样式
                  prefix={
                    <PlusCircleFilled
                      className="cursor-pointer text-[#8C8C8C] hover:text-[#1677ff]"
                      onClick={addGuide}
                      style={{ marginRight: '8px' }}
                    />
                  }
                  suffix={
                    <span className="text-[#8C8C8C] text-xs">
                      {newGuide.length}/50
                    </span>
                  }
                />
              </div>
            </div>
          </div>

          {/* 引导列表 - 设置最大高度和滚动 */}
          <div className="flex-1 overflow-y-auto" style={{ maxHeight: '300px' }}>
            {filteredGuides.map((guide) => (
              <div key={guide.id} className="mb-2 flex items-center rounded-lg bg-[#F1F3F9] p-2">
                <MinusCircleFilled
                  className="mr-3 cursor-pointer text-[#8C8C8C] hover:text-[#ff4d4f]"
                  onClick={() => deleteGuide(guide.id)}
                />
                <Input
                  className="flex-1"
                  value={guide.content}
                  onChange={(e) => updateGuide(guide.id, e.target.value)}
                  maxLength={50}
                  style={guideInputStyle}
                />
              </div>
            ))}
          </div>

          {/* 底部按钮区域 - 固定在底部 */}
          <div className="mt-4 bg-white px-5 pt-4">
            <div className="flex items-center">
              {/* 文件导入按钮 */}
              <div
                className="flex-1 cursor-pointer text-[#4468F5] hover:text-[#1677ff]"
                onClick={handleFileImport}
              >
                从文档导入
                <div className="text-[11px] text-[#A5A9BB]">支持txt与csv</div>
              </div>

              {/* 取消和确定按钮 */}
              <div className="flex flex-1 justify-center space-x-16">
                <Button
                  onClick={onClose}
                // className="rounded-full px-6"
                // style={{ minWidth: '120px', height: '40px', borderRadius: '50px' }}
                >
                  取消
                </Button>
                <Button
                  type="primary"
                  onClick={handleSave}
                // className="rounded-full px-6"
                // style={{ minWidth: '120px', height: '40px', borderRadius: '50px' }}
                >
                  保存
                </Button>
              </div>

              {/* 占位，保持按钮居中 */}
              <div className="flex-1"></div>
            </div>
          </div>
        </div>
      </Modal>

      <ImportGuideModal
        visible={importModalVisible}
        onClose={handleImportClose}
        onImport={handleImportContent}
      />
    </>
  );
};

export default InputGuideModal;
